package com.flashcash.kotlin.utils

import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Looper
import android.support.annotation.RequiresApi
import android.util.Log
import com.flashcash.solu.R
import com.flashcash.solu.common.TokenManager
import com.flashcash.solu.view.login.LoginActivity
import com.flashcash.solu.widget.xleotoast.XLeoToast
import com.tbruyelle.rxpermissions.RxPermissions
import com.x.leo.apphelper.log.XLog
import rx.Subscriber
import java.io.*
import java.lang.ref.SoftReference
import java.text.SimpleDateFormat
import java.util.*

/**
 * @作者:My
 * @创建日期: 2017/7/12 14:20
 * @描述:${TODO}
 *
 * @更新者:${Author}$
 * @更新时间:${Date}$
 * @更新描述:${TODO}
 */
val tokenInstance: TokenManager  by lazy { TokenManager.getInstance() }

fun getToken(): String? = tokenInstance.token

fun Context.dp2Px(dp: Int) = resources.displayMetrics.density * dp

fun timeLongToString(time: Long): String {
    val timeFormator = SimpleDateFormat("yyy-MM-dd HH:mm:ss")
    return timeFormator.format(Date(time))
}

fun getExternalName(path: String): String {
    val split = path.split(".")
    if (split != null && split.size > 0) {
        return split.get(split.size - 1)
    }
    return "";
}

fun Context.startActivityWithCheck(intent: Intent, checkLogin: Boolean) {
    if (checkLogin) {
        if (tokenInstance.hasLogin()) {
            startActivity(intent)
        } else {
            startActivity(Intent(this, LoginActivity::class.java))
        }
    } else {
        startActivity(intent)
    }

}

fun adjustImg(ktp: Bitmap, p2: Int, p3: Int): Bitmap {
    XLog.d("injustImg:started", 10)
    val ops = BitmapFactory.Options()
    val wScale = Math.ceil(ktp.width / p2.toDouble())
    val hScale = Math.ceil(ktp.height / p3.toDouble())
    ops.inSampleSize = (if (wScale > hScale) wScale else hScale).toInt()
    var dao = ByteArrayOutputStream()
    var softBitmap: SoftReference<Bitmap>? = null
    try {
        ktp.compress(Bitmap.CompressFormat.JPEG, 77, dao)
        softBitmap = SoftReference(BitmapFactory.decodeByteArray(dao.toByteArray(), 0, dao.toByteArray().size, ops))
    } catch (e: Exception) {
        e.printStackTrace()
        return ktp
    } finally {
        if (dao != null) {
            try {
                dao.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }

        }
    }
    XLog.d("injustImg:end", 10)
    return softBitmap!!.get()!!
}

fun toJpeg(ctx: Activity, path: String): String? {
    if (Build.VERSION.SDK_INT >= 23 && ctx.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        XLeoToast.showMessage(" write external storage permission not granted,can't use image")
        return null
    }
    var png = BitmapFactory.decodeStream(FileInputStream(File(path)))
    Log.d("UTILS", (png == null).toString())
    val newPath = path.replace(".png", ".jpg")
    val os = FileOutputStream(File(newPath))
    png.compress(Bitmap.CompressFormat.JPEG, 80, os)
    os.flush()
    os.close()
    return newPath
}

@RequiresApi(Build.VERSION_CODES.M)
fun Activity.checkAndRequestPermissions(permission: Array<String>, requestCode: Int) {

    RxPermissions(this)
            .request(*permission)
            .subscribe(object : Subscriber<Boolean>() {
                override fun onError(p0: Throwable?) {
                    XLeoToast.showMessage(R.string.error_occured)
                    this@checkAndRequestPermissions.finish()
                }

                override fun onNext(p0: Boolean?) {
                    if (p0 == false) {
                        val sb = StringBuffer()
                        permission.forEach {
                            sb.append(it.replace("android.permission.", "") + "、")
                        }
                        sb.replace(sb.length - 1, sb.length, "")
                        AlertDialog.Builder(this@checkAndRequestPermissions)
                                .setTitle(R.string.tips_title)
                                .setMessage(String.format(this@checkAndRequestPermissions.getString(R.string.need_permission),
                                        sb.toString()))
                                .setPositiveButton(R.string.button_ok, object : DialogInterface.OnClickListener {
                                    override fun onClick(dialog: DialogInterface?, which: Int) {
                                        dialog?.dismiss()
                                        this@checkAndRequestPermissions.finish()
                                    }
                                }).show()
                    }
                }

                override fun onCompleted() {
                }

            })
}

fun Cursor.printColumn(preString: String) {
    val sb = StringBuilder(preString)
    for (i in 0 until this.columnCount) {
        sb.append("\n" + this.getColumnName(i) + ":" + this.getString(i))
    }
    XLog.i(sb.toString() + preString, 10)
}

fun isSubThread(): Boolean {
    return Looper.getMainLooper() != Looper.myLooper()
}
